# tcp编程

# 创建socket服务

import socket, threading, time
from conf import get_conf

# tuple
socket_conf = get_conf()

# socket instance
socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 服务端绑定端口
socket_server.bind(socket_conf)

# 监听连接数(最大)
socket_server.listen(5)

print('Waiting for connection ...')

def tcplink(sock, addr):
    print('Accept new connection from %s:%s...' % addr)
    msg = 'hello world'
    # 向客户端发送消息
    sock.send(msg.encode('utf-8'))

    while True:
        data = sock.recv(1024)
        time.sleep(.5)
        if not data or data.decode('utf-8') == 'exit':
            break
        rmsg = '%s!' % data.decode('utf-8').strip()
        # print(rmsg)
        sock.send(rmsg.encode('utf-8'))
    # sock.close()

# 持续监听
while True:
    # 接受client请求
    sock, addr = socket_server.accept()
    # 创建新线程来处理tcplink
    t = threading.Thread(target=tcplink, args=(sock, addr))
    # 启动新线程
    t.start()